class TableStore {
  table = null;
  state = {
    items: [],
    ori_items: [],
    columnLen: 0,
    columns: [],
    kits: [],
    sort: {
      prop: null,
      order: null,
      method: null,
      column: null,
    },
  };
  constructor(table) {
    if (!table) {
      throw new Error('table is required for table store!');
    } else {
      this.table = table;
    }
  }
  setSort(prop, order, method) {
    this.state.sort.prop = prop;
    this.state.sort.order = order;
    this.state.sort.method = method;
    const columns = this.state.columns;
    for (let index = 0; index < columns.length; index += 1) {
      if (columns[index].prop === this.state.sort.prop) {
        this.state.sort.column = columns[index];
        break;
      }
    }
  }
  addColumn(column) {
    this.state.columns.push(column);
    /*
    if (this.state.columns.empty) {
      this.state.columns.push(column);
    } else {
      for (let index = 0; index < this.state.columns.length; index += 1) {
        if (this.state.columns[index].id === column.id) {
          this.state.columns.splice(index, 1, column);
          return;
        }
      }
      this.state.columns.push(column);
    }
    */
  }
  addItem(item) {
    this.state.ori_items.push(item);
    this.state.items = this.sort(this.state.ori_items);
  }
  addAllItems(items) {
    items.forEach((item) => {
      this.state.ori_items.push(item);
    });
    this.state.items = this.sort(this.state.ori_items);
  }
  sort(items) {
    if (this.state.sort.column) {
      const order = this.state.sort.order === 'ascending' ? -1 : 1;
      return items.slice().sort((a, b) => {
        return this.state.sort.method(a, b) ? -order : order;
      });
    }
    return items;
  }
  clearItems() {
    const len = this.state.ori_items.length;
    this.state.ori_items.splice(0, len);
    this.state.items.splice(0, len);
  }
}

export default TableStore;
